package com.util;

import android.util.Log;

public class PcMacUtil {
    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};


    public static native byte[] nativeCalMac(byte[] RootKey, byte[] uzKey,byte[] uzRandom);



    public static native byte[] nativeDecodeKey(byte[] RootKey);

    public static native int nativeCalCrc16(byte[] data,int len);


    static {
        System.loadLibrary("PcDes");
    }


    public static PcMacUtil desmac = new PcMacUtil();

    public static String calCRC16(String data){
        Log.d("MM", "calCRC16: data = " + data);
        int nativeCalCrc16 = nativeCalCrc16(StringToBytes(data), StringToBytes(data).length);
        Log.d("MM", "calCRC16: 222 = " + nativeCalCrc16 );
        String s = num2HexStr(nativeCalCrc16, 2);
        Log.d("MM", "calCRC16: 333 = " + s );
        return s;
    }


    /**
     * 将数字转换成byteLen字节长度的十六进制数
     *
     * @param num
     * @param byteLen
     * @return
     */
    public static String num2HexStr(int num, int byteLen) {
        String hexNum = Integer.toHexString(num);
        while (hexNum.length() < byteLen * 2) {
            hexNum = "0" + hexNum;
        }
        return hexNum.toUpperCase();
    }


    public static String calMac(String rootKey,String uzKey,String uzRandom){
        return HexToString(nativeCalMac(StringToBytes(rootKey),
                StringToBytes(uzKey),
                StringToBytes(uzRandom)
                ));
    }


    public static String decodeKey(String rootKey){
        return HexToString(nativeDecodeKey(StringToBytes(rootKey)));
    }



    private static byte[] StringToBytes(String str) {
        int nLen = str.length();
        byte bytes[] = new byte[str.length() / 2];
        for (int i = 0; i < nLen / 2; i++) {
            bytes[i] = StringToByte(str.substring(i * 2, i * 2 + 2));
        }
        return bytes;
    }

    private static byte StringToByte(String str) {
        return (byte) Integer.parseInt(str, 16);
    }

    private static String HexToString(byte[] inHex) {
        byte i;
        String strResult = "";
        for (i = 0; i < inHex.length; i++) {
            strResult += String.valueOf(DIGITS_UPPER[(0xF0 & inHex[i]) >>> 4])
                    + String.valueOf(DIGITS_UPPER[inHex[i] & 0x0F]);
        }
        return strResult;
    }


}
